package cn.doitedu.demos;

import java.util.Arrays;
import java.util.Collections;

/***
 * @author hunter.d
 * @qq 657270652
 * @wx haitao-duan
 * @date 2020/12/23
 **/
public class SqlBuilder {

    private StringBuilder select = new StringBuilder();
    private StringBuilder from = new StringBuilder();
    private StringBuilder fromsub = new StringBuilder();
    private StringBuilder join = new StringBuilder();
    private StringBuilder on = new StringBuilder();
    private StringBuilder where = new StringBuilder();
    private StringBuilder and = new StringBuilder();


    public SqlBuilder from(String table){
        from.append(table);
        return this;
    }

    public SqlBuilder fromSubquery(String subQuery){
        fromsub.append("\n  ( \n"+ subQuery +"\n ) o \n");
        return this;
    }

    public SqlBuilder where(String exp){
        where.append(exp);
        return this;
    }

    public SqlBuilder and(String exp){
        and.append(" and " +exp);
        return this;
    }


    public SqlBuilder select(String... fields ){
        for (String field : fields) {
            select.append(field).append(",");
        }
        return this;
    }

    public String build(){
        String sel = select.substring(0, select.length() - 1);

        String s = "";
        if(fromsub.length()>0) {
            s = "select " + sel + " from " + fromsub.toString() + " where " + where.toString() + and.toString();
        }else{
            s = "select " + sel + " from " + from.toString() + " where " + where.toString() + and.toString();
        }
        return s;
    }


    public static void main(String[] args) {

        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.from("t1");
        sqlBuilder.select("id","name","max(age)").select("age");
        sqlBuilder.where("age > '30'");
        sqlBuilder.and("sex = 'male' ");
        sqlBuilder.and("province = 'shanxi' ");

        System.out.println(sqlBuilder.build());

        SqlBuilder sqlBuilder1 = new SqlBuilder();
        sqlBuilder1.fromSubquery(sqlBuilder.build()).select("id","name").where("city='changsha'").and("1=1");

        System.out.println(sqlBuilder1.build());


    }

}
